#!/usr/bin/env python
# vim: set filetype=python expandtab tabstop=2 shiftwidth=2 autoindent smartindent:
# -*- coding: utf-8 -*-
#
# test json rpc call  

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from django.utils import simplejson

  
class RPCHandler(webapp.RequestHandler):
  """ Allows the functions defined in the RPCMethods class to be RPCed."""

  def __init__(self):
    webapp.RequestHandler.__init__(self)
    self.methods = RPCMethods()
 
  def get(self):
    func = None

    action = self.request.get('action')
    if action:
      if action[0] == '_':
        self.error(403) # access denied
        return
      else:
        func = getattr(self.methods, action, None)
   
    if not func:
      self.error(404) # file not found
      return
     
    args = {}
    keys = self.request.arguments()

    for arg in keys:
      if arg != 'action':
        args[arg] = self.request.get(arg)

    result = func(args)
    self.response.out.write(simplejson.dumps(result))
    
  def post(self):
    args = simplejson.loads(self.request.body)
    #func, args = args[0], args[1:]
    func = args['action']
    del args['action']
   
    if func[0] == '_':
      self.error(403) # access denied
      return
     
    func = getattr(self.methods, func, None)
    if not func:
      self.error(404) # file not found
      return

    result = func(args)
    self.response.out.write(simplejson.dumps(result))

class RPCMethods:
  """ Defines the methods that can be RPCed.
  NOTE: Do not allow remote callers access to private/protected "_*" methods.
  """
  def Add(self, *args):
    # The JSON encoding may have encoded integers as strings.
    # Be sure to convert args to any mandatory type(s).
    #ints = [int(arg) for arg in args]
    #return int(args[0]) + int(args[1])
    tagsdic = args[0]
    sum = 0
    for key in tagsdic:
      sum += int(tagsdic[key])

    #return sum
    return '{"sum": "%d"}' % sum

  def Sub(self, *args):
    tagsdict = args[0]
    


def main():
  # path router
  application = webapp.WSGIApplication([
    ('/rpc', RPCHandler)
  ], debug=True)
  run_wsgi_app(application)


if __name__ == '__main__':
  main()
      
